<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<meta name="viewport" content="maximum-scale=1.0, minimum-scale=1.0, user-scalable=0, initial-scale=1.0, width=device-width" />
		<meta name="format-detection" content="telephone=no, email=no, date=no, address=no">
		<title>绘制时钟</title>
	</head>
	<body>
		<canvas id="canvas" width="800" height="800"></canvas>
	</body>
	<script type="text/javascript">
		const pi2 =2*Math.PI
		let canvas = document.getElementById('canvas')
		let ctx = canvas.getContext('2d')
		console.log(ctx)
		function drawclock(){
			ctx.clearRect(0,0,800,800)
			//保存初始状态
			ctx.save()
			// 绘制表盘
			ctx.translate(400,400)
			ctx.save()
			ctx.arc(0,0,200,0,pi2)
			
			//绘制秒、分针刻度
			for(let i=0;i<60;i++){
				ctx.rotate(pi2/60*i)
				ctx.beginPath()
				ctx.moveTo(190,0)
				ctx.lineTo(210,0)
				ctx.lineWidth=2
				ctx.strokeStyle='darkgray'
				ctx.stroke()
				ctx.closePath()
				ctx.restore()
				ctx.save()
			}
			//绘制时针刻度
			for(let i=0;i<12;i++){
				ctx.rotate(pi2/12*i)
				ctx.beginPath()
				ctx.moveTo(180,0)
				ctx.lineTo(210,0)
				ctx.lineWidth=8
				ctx.stroke()
				ctx.closePath()
				ctx.restore()
				ctx.save()
			}
			
			
			
			let time = new Date()
			let hour = time.getHours()
			let min = time.getMinutes()
			let sec = time.getSeconds()
			hour=hour>12?hour-12:hour
			console.log(hour+':'+min+':'+sec)
			
			//绘制秒针
			ctx.rotate(-pi2/4)
			ctx.rotate(pi2/60*sec)
			ctx.beginPath()
			ctx.moveTo(-20,0)
			ctx.lineTo(180,0)
			ctx.strokeStyle='#f44'
			ctx.stroke()
			ctx.closePath()
			ctx.restore()
			ctx.save()
			
			//绘制分针
			ctx.rotate(-pi2/4)
			ctx.rotate(pi2/60*min+pi2/60/60*sec)
			ctx.beginPath()
			ctx.lineWidth=4
			ctx.moveTo(-15,0)
			ctx.lineTo(160,0)
			ctx.stroke()
			ctx.closePath()
			ctx.restore()
			ctx.save()
			
			//绘制时针
			ctx.rotate(-pi2/4)
			ctx.rotate(pi2/12*hour+pi2/12/60*min+pi2/12/60/60*sec)
			ctx.beginPath()
			ctx.lineWidth=6
			ctx.moveTo(-10,0)
			ctx.lineTo(150,0)
			ctx.stroke()
			ctx.closePath()
			
			ctx.restore()
			ctx.restore()
		}
		
		drawclock()
		setInterval(drawclock,1000)
	</script>
</html>
